package com.yxw.live_vod_boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_boot.dto.*;
import com.yxw.live_vod_boot.entity.*;
import com.yxw.live_vod_boot.mapper.*;
import com.yxw.live_vod_boot.service.OnDemandVideoReviewService;
import com.yxw.live_vod_boot.service.OnDemandVideoService;
import com.yxw.live_vod_boot.service.ProductService;
import com.yxw.live_vod_boot.service.SysNoticeService;
import com.yxw.live_vod_boot.utils.*;
import com.yxw.live_vod_boot.vo.OnDemandPlayVo;
import com.yxw.live_vod_boot.vo.OnDemandVideoVo;
import com.yxw.live_vod_boot.vo.VideoPalyStatisticsVo;
import com.yxw.live_vod_boot.vo.VolcanoVideoInfoVO;
import com.yxw.live_vod_facade.dto.PageVodInfoListDto;
import com.yxw.live_vod_facade.dto.VideoDeleteDTO;
import com.yxw.live_vod_facade.enums.NoticeTypeEnum;
import com.yxw.live_vod_facade.vo.*;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.FileClassifyEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseDateTime;
import com.yxw.yxnet_cd_center.common.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 点播视频管理
 * @author liuxin
 * @date 2023.11.15
 */
@Slf4j
@Service
public class OnDemandVideoServiceImpl extends ServiceImpl<OnDemandVideoMapper, YxOnDemandVideoEntity> implements OnDemandVideoService {


    /**
     * 视频文件最大大小
     */
    @Value("${file.video.max.size}")
    private long fileVideoMaxSize;

    /**
     * 图片文件最大大小
     */
    @Value("${file.image.max.size}")
    private long fileImageMaxSize;

    @Autowired
    private HuaWeiObsUtil huaWeiObsUtil;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OnDemandVideoReviewService onDemandVideoReviewService;

    @Autowired
    private OnDemandVideoReviewMapper onDemandVideoReviewMapper;

    @Autowired
    private VolcanoEngineUtil volcanoEngineUtil;

    @Autowired
    private VodPalyMapeer vodPalyMapeer;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private SysNoticeService sysNoticeService;

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private OnDemandVideoMapper onDemandVideoMapper;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private VodProductMapper vodProductMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private VodProductClickMapper vodProductClickMapper;

    @Autowired
    private ProductService productService;
    

    /**
     * 视频上传
     * @param videoFile
     * @param dto
     * @return
     */
    @Override
    public VideoReviewVO uploadVideo(MultipartFile videoFile, UploadVideoDTO dto){
        Long userId = userUtil.getLoginUserId();
        if(null==userId){
            throw new BaseException("用户未登录,不能上传");
        }
        //视频和封面校验
        StringBuffer sbf=new StringBuffer();
        sbf.append(FileUtils.validataVideo(videoFile,fileVideoMaxSize));
        //查询点播空间
        LambdaQueryWrapper<YxLiveShopEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true,YxLiveShopEntity::getLiveShopId,dto.getShopId());
        YxLiveShopEntity shopEntity = shopMapper.selectOne(queryWrapper);
        if(null==shopEntity){
            sbf.append("未查询到店铺信息<br>");
        }else{
            if(shopEntity.getUserId().compareTo(userId)!=0){
                sbf.append("上传人不是店铺负责人,视频不能上传到该店铺<br>");
            }else{
                BigDecimal videoSize =new BigDecimal(videoFile.getSize()/1024.0/1024.0);//视频大小
                if(videoSize.compareTo(shopEntity.getRemainStorage())>0){
                    sbf.append("点播空间已不足,剩余"+shopEntity.getRemainStorage()+"M，请重新选择视频或删除作品<br>");
                }
            }
        }
        if(StringUtils.isNotBlank(sbf.toString())){
            throw new BaseException(sbf.toString());
        }
        VideoReviewVO vo=new VideoReviewVO();
        try {
            //视频上传华为云
            FileClassifyEnum videoEnum = FileClassifyEnum.getEnumByCode(CommonConstant.ONE);
            String videoKey = videoEnum.getPath() + UUID.randomUUID().toString().replace("-", "") + videoFile.getOriginalFilename().substring(videoFile.getOriginalFilename().lastIndexOf(CommonConstant.POINT));
            String videoPath = huaWeiObsUtil.uploadFile(videoKey, videoFile.getInputStream());
            log.info("视频videoKey=================================>"+videoKey);
            log.info("视频videoPath=================================>"+videoPath);
            //文件都上传成功以后写审核数据
            VideoReviewDTO reviewDTO = new VideoReviewDTO();
            reviewDTO.setDto(dto);
            reviewDTO.setVideoPath(videoPath);
            reviewDTO.setCoverPath(dto.getCoverUrl());
            reviewDTO.setVideoFile(videoFile);
            reviewDTO.setVideoKey(videoKey);
            vo=onDemandVideoReviewService.addVideoReview(reviewDTO);
            //添加商品
            if(null!=dto.getProductId()){
                AddVodProductDto addVodProductDto = new AddVodProductDto();
                addVodProductDto.setProductId(dto.getProductId());
                addVodProductDto.setReviewVideoId(vo.getReviewVideoId());
                productService.addVodProduct(addVodProductDto);
            }
        }catch (Exception e){
            log.error("系统异常："+e.getMessage());
            throw new BaseException("系统异常："+e.getMessage());
        }
        return vo;
    }


    /**
     * 图片文件上传
     * @param file
     * @return
     */
    @Override
    public String uploadImages(MultipartFile file) {
        Long userId = userUtil.getLoginUserId();
        if(null==userId){
            throw new BaseException("用户未登录,不能上传");
        }
        //图片校验
        String msg = FileUtils.validataCover(file, fileImageMaxSize);
        if(StringUtils.isNotBlank(msg)){
            throw new BaseException(msg);
        }
        String imagesUrl="";
        try {
            //封面上传华为云
            FileClassifyEnum coverEnum = FileClassifyEnum.getEnumByCode(CommonConstant.TWO);
            String imagesKey = coverEnum.getPath() + UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(CommonConstant.POINT));
            imagesUrl = huaWeiObsUtil.uploadFile(imagesKey, file.getInputStream());
            log.info("图片coverKey=================================>" + imagesKey);
            log.info("图片coverPath=================================>" + imagesUrl);
        }catch (Exception e){
            log.error("上传图片错误{}",e.getMessage());
            throw new BaseException("上传图片错误:"+e.getMessage());
        }
        return imagesUrl;
    }

    /**
     * 店铺点播视频列表
     * @param dto
     * @return
     */
    @Override
    public PageVO<OnDemandVideoVo> pageVideo(OndemandVideoQueryDTO dto) {
        List<OnDemandVideoVo> volist=new ArrayList<>();
        Page<YxOnDemandVideoEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        QueryWrapper<YxOnDemandVideoEntity> queryWrapper =new  QueryWrapper<>();
        queryWrapper.eq(true,"shop_id",dto.getShopId());
        queryWrapper.eq(true,"video_status",CommonConstant.ONE);
        //游客查询已发布视频，店铺负责人可以看到全部
//        queryWrapper.and(vod->{
//            vod.eq("user_id",userUtil.getLoginUserId());
//            vod.or(v->{
//                v.ne("user_id", userUtil.getLoginUserId()).eq("publish_status", CommonConstant.TWO);
//            });
//        });
        queryWrapper.orderByDesc("top_flag").orderByDesc("create_time");
        queryWrapper.select(
                "yx_on_demand_video.*",
                "(select count(1) from yx_on_demand_play dp where dp.video_id=yx_on_demand_video.video_id) as playCnt",
                "(select count(1) from yx_video_like yvl where  yvl.video_id=yx_on_demand_video.video_id) as likeCnt" ,
                 "(select count(1) from yx_sys_share sr where  sr.buss_id=yx_on_demand_video.video_id) as shareCnt" ,
                "(select count(1) from yx_on_demand_collection_video  cv where cv.video_id =yx_on_demand_video.video_id) as collectionCnt",
                "(select count(1) from yx_on_demand_comment  dc where dc.video_id=yx_on_demand_video.video_id) as commentCnt",
                "(select ls.shop_avatar from yx_live_shop ls where ls.live_shop_id=yx_on_demand_video.shop_id) as shopHeadUrl"
        );
        Page<YxOnDemandVideoEntity> entityPage = onDemandVideoMapper.selectPage(page, queryWrapper);
        if(null!=entityPage.getRecords() && !entityPage.getRecords().isEmpty()){
            volist = BeanUtil.copyToList(entityPage.getRecords(), OnDemandVideoVo.class);
            //商品信息
            for (OnDemandVideoVo vo: volist) {
                LambdaQueryWrapper<YxVodProductEntity> queryProWrapper=new LambdaQueryWrapper();
                queryProWrapper.eq(YxVodProductEntity::getVideoId,vo.getVideoId());
                YxVodProductEntity yxVodProductEntity = vodProductMapper.selectOne(queryProWrapper);
                if(null!=yxVodProductEntity){
                    VodProductVo productVo = new VodProductVo();
                    BeanUtils.copyProperties(yxVodProductEntity, productVo);
                    vo.setProInfo(productVo);
                }
                //vo.setIsLike(redisManager.existBySet(RedisIdConstant.ON_DEMAND_VIDEO_LIKE+":"+ vo.getVideoId(), userUtil.getLoginUserId()));
            }
        }
        return PageUtils.get(page,volist);
    }

    /**
     * 批量删除视频
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteVideoByIds(VideoDeleteDTO dto) {
        //删除的时候填充删除人
        Integer delType = dto.getDelType();
        if(CommonConstant.TWO==delType){
            dto.setUserId(userUtil.getLoginUserId());
            dto.setUserName(userUtil.getLoginName());
        }
        //单个删除，需要删除华为云文件和火山上传文件（不删封面）
        List<Long> videoIdList = dto.getVideoIdList();
        for (Long videoId:videoIdList) {
            //查询上传视频信息
            YxOnDemandVideoEntity videoEntity = baseMapper.selectById(videoId);
            if(null!=videoEntity){
                //通过审核信息先删除华为云文件，然后作废审核信息
                YxUploadVideoReviewEntity reviewEntity = onDemandVideoReviewMapper.selectById(videoEntity.getReviewVideoId());
                if(null!=reviewEntity){
                    String videoKey = reviewEntity.getVideoKey();
                    String coverKey = reviewEntity.getCoverKey();
                    try{
                        huaWeiObsUtil.deleteFile(videoKey);
//                        huaWeiObsUtil.deleteFile(coverKey);
                    }catch (Exception e){
                        log.error("华为云文件删除失败：==============================================>"+e.getMessage());
                    }
                    reviewEntity.setExamineStatus(3);
                    onDemandVideoReviewMapper.updateById(reviewEntity);
                }
            }
        }
        List<YxOnDemandVideoEntity> videoList=null;
        try {
            //删除火引擎的视频文件
            LambdaQueryWrapper<YxOnDemandVideoEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(true, YxOnDemandVideoEntity::getVideoId, videoIdList);
            queryWrapper.in(true, YxOnDemandVideoEntity::getShopId, dto.getShopId());
            videoList = baseMapper.selectList(queryWrapper);
            List<String> vidList = videoList.stream().map(video -> video.getVId()).collect(Collectors.toList());
            volcanoEngineUtil.deleteMedia(vidList,null);
        }catch (Exception e){
            log.error("火山引擎文件删除失败：==============================================>"+e.getMessage());
        }
        //修改视频数据为作废
        LambdaUpdateWrapper<YxOnDemandVideoEntity> updateWrapper =new  LambdaUpdateWrapper<>();
        updateWrapper.set(YxOnDemandVideoEntity::getVideoStatus,delType);
        updateWrapper.set(YxOnDemandVideoEntity::getUpdateId,dto.getUserId());
        updateWrapper.set(YxOnDemandVideoEntity::getUpdateName,dto.getUserName());
        updateWrapper.set(YxOnDemandVideoEntity::getUpdateTime,new Date());
        updateWrapper.in(YxOnDemandVideoEntity::getVideoId,videoIdList);
        updateWrapper.in(YxOnDemandVideoEntity::getShopId,dto.getShopId());
        baseMapper.update(null,updateWrapper);
        //修改店铺可用容量
        LambdaQueryWrapper<YxLiveShopEntity> shopQueryWrapper = new LambdaQueryWrapper<>();
        shopQueryWrapper.eq(true,YxLiveShopEntity::getLiveShopId,dto.getShopId());
        YxLiveShopEntity shopEntity = shopMapper.selectOne(shopQueryWrapper);
        if(null!=shopEntity){
            BigDecimal remainStorage=new BigDecimal(0);
            for (int i = 0; i <videoList.size() ; i++) {
                BigDecimal videoSize = null==videoList.get(i).getVideoSize()?new BigDecimal(0):videoList.get(i).getVideoSize();
                remainStorage=remainStorage.add(videoSize);
            }
            shopEntity.setRemainStorage(remainStorage);
            shopMapper.updateById(shopEntity);
        }
        if(3==delType){
            //发送下架通知
            for (int i = 0; i <dto.getVideoIdList().size() ; i++) {
                Long videoId = dto.getVideoIdList().get(0);
                SendInteractMsgDto msgDto = new SendInteractMsgDto();
                msgDto.setBussId(String.valueOf(videoId));
                msgDto.setShopName(shopEntity.getShopName());
                msgDto.setShopId(shopEntity.getLiveShopId());
                msgDto.setUserId(shopEntity.getUserId());
                msgDto.setUserName(shopEntity.getUserName());
                msgDto.setType(NoticeTypeEnum.VOD_OFF_SHELf);
                sysNoticeService.sendNotice(msgDto);
            }
        }
    }

    /**
     *点播作品统计
     * @param videoId
     * @return
     */
    @Override
    public VideoPalyStatisticsVo getVideoPlayStatistics(Long videoId) {
        VideoPalyStatisticsVo vo=onDemandVideoMapper.getVideoPlayStatistics(videoId);
        if(vo!=null){
            Integer playCnt = vo.getPlayCnt();
            if(CommonConstant.ZERO!=playCnt){
                //完播率
                vo.setCompletePlatRate(String.format("%.2f",vo.getCompleteCnt()/playCnt*100.00)+"%");
                //平均播放时长
                BigDecimal totalDuration = vo.getTotalDuration();
                vo.setAvgDuration(totalDuration.divide(BigDecimal.valueOf(playCnt),2,BigDecimal.ROUND_HALF_UP));
                //点赞率
                vo.setLikeRate(String.format("%.2f",vo.getLikeCnt()/playCnt*100.00)+"%");
                //分享率
                vo.setShareRate(String.format("%.2f",vo.getShareCnt()/playCnt*100.00)+"%");
            }else{
                vo.setCompletePlatRate("0%");
                vo.setAvgDuration(BigDecimal.valueOf(0));
                vo.setLikeRate("0%");
                vo.setShareRate("0%");
            }
            Integer clickCnt = vo.getClickCnt();
            if(0!=clickCnt){
                vo.setClickBuyRate(String.format("%.2f",vo.getBuyCnt()/clickCnt*100.00)+"%");
            }else{
                vo.setClickBuyRate("0%");
            }
        }
        return vo;

    }

    /**
     * 视频修改
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVideoById(UpdateVideoDTO dto) {
        YxOnDemandVideoEntity videoEntity = baseMapper.selectById(dto.getVideoId());
        if(null==videoEntity){
            throw new BaseException("视频不存在");
        }
        //置顶
        if(null!=dto.getTopFlag()){
            videoEntity.setTopFlag(dto.getTopFlag());
        }
        //隐私设置
        if(null!=dto.getPublicFlag()){
            videoEntity.setPublicFlag(dto.getPublicFlag());
        }
        //标题
        if(StringUtils.isNotBlank(dto.getTitel())){
            videoEntity.setTitel(dto.getTitel());
        }
        videoEntity.setUpdateTime(new Date());
        baseMapper.updateById(videoEntity);
    }

    /**
     * 店铺点播作品列表详情查询
     * @param dto
     * @return
     */
    @Override
    public PageVO<PageVodInfoListVO> pageVodInfoList(PageVodInfoListDto dto) {
        List<PageVodInfoListVO> voList=new ArrayList<>();
        Page<YxOnDemandVideoEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        LambdaQueryWrapper<YxOnDemandVideoEntity> vodQuery=new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(dto.getTitel())){
            vodQuery.like(YxOnDemandVideoEntity::getTitel,dto.getTitel().trim());
        }
        if(StringUtils.isNotBlank(dto.getShopName())){
            vodQuery.like(YxOnDemandVideoEntity::getShopName,dto.getShopName().trim());
        }
        vodQuery.ge(null!=dto.getCreateTimeStart(), YxOnDemandVideoEntity::getCreateTime, dto.getCreateTimeStart());
        vodQuery.le(null!=dto.getCreateTimeEnd(), YxOnDemandVideoEntity::getCreateTime, dto.getCreateTimeEnd());
        if(StringUtils.isNotBlank(dto.getMerchantName())){
            LambdaQueryWrapper<YxLiveShopEntity> shopQuery=new LambdaQueryWrapper();
            shopQuery.like(YxLiveShopEntity::getMerchantName,dto.getMerchantName());
            List<YxLiveShopEntity> shopList = shopMapper.selectList(shopQuery);
            vodQuery.in(YxOnDemandVideoEntity::getShopId,shopList.stream().map(shop->shop.getLiveShopId()).collect(Collectors.toList()));
        }
        vodQuery.orderByDesc(YxOnDemandVideoEntity::getCreateTime);
        Page<YxOnDemandVideoEntity> entityPage = baseMapper.selectPage(page, vodQuery);
        if(null!=entityPage.getRecords() && !entityPage.getRecords().isEmpty()){
            voList = BeanUtil.copyToList(entityPage.getRecords(), PageVodInfoListVO.class);
            //查询点播相关信息进行封装
            for (PageVodInfoListVO vo:voList ) {
                //查询统计数据
                VideoPalyStatisticsVo videoPlayStatistics = this.getVideoPlayStatistics(vo.getVideoId());
                //播放次数
                vo.setPlayCnt(videoPlayStatistics.getPlayCnt());
                //完成播放次数
                vo.setCompletePlatRate(videoPlayStatistics.getCompletePlatRate());
                //评论量
                vo.setCommentCnt(videoPlayStatistics.getCommentCnt());
                //点赞量
                vo.setLikeCnt(videoPlayStatistics.getLikeCnt());
                //分享量
                vo.setShareCnt(videoPlayStatistics.getShareCnt());
                //收藏量
                vo.setCollectionCnt(videoPlayStatistics.getCollectionCnt());
                //是否存在上架商品
                LambdaQueryWrapper<YxVodProductEntity> proWapper=new LambdaQueryWrapper();
                proWapper.eq(YxVodProductEntity::getVideoId,vo.getVideoId());
                proWapper.eq(YxVodProductEntity::getStatus,CommonConstant.ONE);
                Integer proCnt = vodProductMapper.selectCount(proWapper);
                if(proCnt>=0){
                    vo.setExistsProduct(1);
                }else{
                    vo.setExistsProduct(0);
                }
            }
        }
        return PageUtils.get(page,voList);
    }

    /**
     * URL上传火山引擎后回调接口
     * @param json
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void fileUploadByUrlComplete(String json) {
        log.info("回调开始{}=====================================>{}",BaseDateTime.getLongDateTimeString(),json);
        //解析vid
        Map jsonMap = JSONObject.parseObject(json, Map.class);
        if(null!=jsonMap){
            Map dataMap = JSONObject.parseObject(String.valueOf(jsonMap.get("Data")), Map.class);
            if(null!=dataMap){
               String jobId=String.valueOf(dataMap.get("JobId"));
               String vid=String.valueOf(dataMap.get("Vid"));
               if(StringUtils.isNotBlank(jobId) && StringUtils.isNotBlank(vid) ){
                    //查询视频
                   LambdaQueryWrapper<YxOnDemandVideoEntity> queryWrapper=new LambdaQueryWrapper();
                   queryWrapper.eq(YxOnDemandVideoEntity::getJobId,jobId);
                   YxOnDemandVideoEntity videoEntity = baseMapper.selectOne(queryWrapper);
                   if(null!=videoEntity){
                       //发布
                       volcanoEngineUtil.publishStatus(vid,videoEntity.getReviewVideoId());
                       //查询播放地址
                       VolcanoVideoInfoVO playInfo = volcanoEngineUtil.getPlayInfo(vid, videoEntity.getReviewVideoId());
                       videoEntity.setPlayUrl(playInfo.getPlayUrl());
                       videoEntity.setVId(vid);
                       videoEntity.setDuration(playInfo.getDuration());
                       baseMapper.updateById(videoEntity);
                   }
               }
            }
        }
        log.info("回调结束=====================================>"+ BaseDateTime.getLongDateTimeString());
    }

    /**
     * 点播视频播放记录
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OnDemandPlayVo saveVodPlay(AddVodPlayDto dto) {
        YxOnDemandPlayEntity playEntity=new YxOnDemandPlayEntity();
        //结束播放
        if(null!=dto.getPlayId()){
            playEntity=vodPalyMapeer.selectById(dto.getPlayId());
            playEntity.setPlayEndTime(new Date());
            //时长
            Date nowDate = new Date();
            long playDuration= (nowDate.getTime() - playEntity.getPlayStartTime().getTime()) / 1000;
            playEntity.setPlayDuration(new BigDecimal(playDuration));
            //查询视频信息
            YxOnDemandVideoEntity videoEntity = baseMapper.selectById(playEntity.getVideoId());
            Float videoDuration = videoEntity.getDuration();
            //播放完成80%就算完播
            if(playEntity.getPlayDuration().divide(new BigDecimal(videoDuration)).compareTo(new BigDecimal("0.8"))>0){
                playEntity.setCompleteFlag(1);
            }else{
                playEntity.setCompleteFlag(0);
            }
            vodPalyMapeer.updateById(playEntity);
        }else{
            //查询视频信息
            YxOnDemandVideoEntity videoEntity = baseMapper.selectById(dto.getVideoId());
            playEntity.setPlayUrl(videoEntity.getPlayUrl());
            playEntity =new  YxOnDemandPlayEntity();
            playEntity.setVideoId(dto.getVideoId());
            playEntity.setPlayUserId(String.valueOf(userUtil.getLoginUserId()));
            playEntity.setPlayUserName(userUtil.getLoginName());
            playEntity.setPlayStartTime(new Date());
            playEntity.setCreateTime(new Date());
            vodPalyMapeer.insert(playEntity);
        }
        OnDemandPlayVo vo = new OnDemandPlayVo();
        BeanUtil.copyProperties(playEntity, vo);
        return vo;
    }

    /**
     * 热门视频10条
     * 关注视频：5条
     * 最新视频：8条
     * 点播视频推荐列表查询
     * @return
     */
    @Override
    public Set<RecommendVodListVo> pageVodRecommendList() {
        Set<RecommendVodListVo> voList=new HashSet<>();
        //获取当前用户
        Long userId = userUtil.getLoginUserId();
        if(null==userId){
            throw new BaseException("用户未登录,查询推荐页视频失败");
        }
        //查询推荐视频-已关注用户的视频最新一条
        Set<RecommendVodListVo> redisFollowVodList = redisTemplate.opsForSet().members(RedisIdConstant.VOD_FOLLOW+userId);
        if(null==redisFollowVodList || redisFollowVodList.isEmpty()){
            //没有缓存从数据库查询
            List<RecommendVodListVo> followVodList=onDemandVideoMapper.getFollowVodList(userId);
            if(null==followVodList || followVodList.isEmpty()){
                //没有就往redis放空数据
                redisTemplate.opsForSet().add(RedisIdConstant.VOD_FOLLOW+userId,"无数据");
                //两小时过期
                redisTemplate.expire(RedisIdConstant.VOD_FOLLOW+userId, 2*60*60,TimeUnit.SECONDS);
            }else{
                //放入redis 缓存两个小时
                for (RecommendVodListVo vo:followVodList) {
                    redisTemplate.opsForSet().add(RedisIdConstant.VOD_FOLLOW+userId,vo);
                    //两小时过期
                    redisTemplate.expire(RedisIdConstant.VOD_FOLLOW+userId, 2*60*60,TimeUnit.SECONDS);
                }
            }
        }
        //推荐视频
        redisFollowVodList = redisTemplate.opsForSet().members(RedisIdConstant.VOD_FOLLOW+userId);
        //关注推荐计数
        int followCnt=1;
        if(!redisFollowVodList.contains("无数据")) {
            Iterator<RecommendVodListVo> iterator = redisFollowVodList.iterator();
            while (iterator.hasNext()) {
                //只取五条
                if (followCnt >= 5) {
                    break;
                }
                RecommendVodListVo vo = iterator.next();
                //取人员ID+视频ID的hash值判断是否已经推荐过
                int hashCode = Math.abs(String.valueOf(vo.getVideoId() + userId).hashCode());
                //查询该视频是否已经播放过
//                Boolean lookFlag = redisTemplate.opsForValue().getBit(RedisIdConstant.PLAT_VOD_RECOMMEND + userId, hashCode);
//                //播放过了
//                if (null != lookFlag && lookFlag) {
//                    continue;
//                }
                //是否点赞
                vo.setIsLike(redisManager.existBySet(RedisIdConstant.ON_DEMAND_VIDEO_LIKE + ":" + vo.getVideoId(), userId));
                //是否收藏
                //放入推荐列表
                voList.add(vo);
                //放入已推荐缓存
                redisTemplate.opsForValue().setBit(RedisIdConstant.PLAT_VOD_RECOMMEND + userId, hashCode, true);
                followCnt = followCnt + 1;
            }
        }
        //取热门视频
        Set<RecommendVodListVo> popularVodList = redisTemplate.opsForSet().members(RedisIdConstant.POPULAR_VOD_RECOMMEND);
        //热门计数
        int popularCnt=1;
        if(null!=popularVodList && !popularVodList.isEmpty()){
            Iterator<RecommendVodListVo> iterator = popularVodList.iterator();
            while (iterator.hasNext()) {
                if(popularCnt>=10){
                    break;
                }
                RecommendVodListVo vod = iterator.next();
                int hashCode = Math.abs(String.valueOf(vod.getVideoId() + userId).hashCode());
                //查询该视频是否已经播放过
//                Boolean lookFlag = redisTemplate.opsForValue().getBit(RedisIdConstant.PLAT_VOD_RECOMMEND + userId, hashCode);
//                //播放过了
//                if(null!=lookFlag && lookFlag){
//                    continue;
//                }
                //是否点赞
                vod.setIsLike(redisManager.existBySet(RedisIdConstant.ON_DEMAND_VIDEO_LIKE+":"+ vod.getVideoId(), userId));
                //放入推荐列表
                voList.add(vod);
                //放入已推荐缓存
                redisTemplate.opsForValue().setBit(RedisIdConstant.PLAT_VOD_RECOMMEND + userId, hashCode,true);
                popularCnt=popularCnt+1;
            }
        }
        //取最新视频
        Set<RecommendVodListVo> newVodList = redisTemplate.opsForSet().members(RedisIdConstant.NEW_VOD_RECOMMEND);
        //热门计数
        int newCnt=1;
        if(null!=newVodList && !newVodList.isEmpty()){
            Iterator<RecommendVodListVo> iterator = newVodList.iterator();
            while (iterator.hasNext()) {
                if(popularCnt>=8){
                    break;
                }
                RecommendVodListVo vod = iterator.next();
                int hashCode = Math.abs(String.valueOf(vod.getVideoId() + userId).hashCode());
                //查询该视频是否已经播放过
//                Boolean lookFlag = redisTemplate.opsForValue().getBit(RedisIdConstant.PLAT_VOD_RECOMMEND + userId, hashCode);
//                //播放过了
//                if(null!=lookFlag && lookFlag){
//                    continue;
//                }
                //是否点赞
                vod.setIsLike(redisManager.existBySet(RedisIdConstant.ON_DEMAND_VIDEO_LIKE+":"+ vod.getVideoId(), userId));
                //放入推荐列表
                voList.add(vod);
                //放入已推荐缓存
                redisTemplate.opsForValue().setBit(RedisIdConstant.PLAT_VOD_RECOMMEND + userId, hashCode,true);
                newCnt=newCnt+1;
            }
        }
        return voList;
    }

    /**
     *  热门视频：高赞高转发高播放视频（播放量>1000，点赞率>20%，转发率>5%，发布时间2周内）
     * 最新视频（3天内发布的视频）
     * 抽取热门数据和最新数据放入缓存(每天凌晨执行一次)
     */
    @Override
    public void extractVodByDay() {
        //查询热门视频
        Set<RecommendVodListVo> popularVodList=onDemandVideoMapper.getPopularVodList();
        redisTemplate.delete(RedisIdConstant.POPULAR_VOD_RECOMMEND);
        for (RecommendVodListVo vo :popularVodList) {
            redisTemplate.opsForSet().add(RedisIdConstant.POPULAR_VOD_RECOMMEND,vo);
        }
        //最新视频
        Set<RecommendVodListVo> newVodList=onDemandVideoMapper.getNewVodList();
        redisTemplate.delete(RedisIdConstant.NEW_VOD_RECOMMEND);
        for (RecommendVodListVo vo :newVodList) {
            redisTemplate.opsForSet().add(RedisIdConstant.NEW_VOD_RECOMMEND,vo);
        }
    }

    /**
     * 查询点播上架商品和订单统计信息
     * @param videoId
     * @return
     */
    @Override
    public VodSalesRevenueVo getVodProductOrderByVideoId(Long videoId) {
        //查询点播成交订单信息
        VodSalesRevenueVo vo=orderMapper.getVodOrderByVideoId(videoId);
        //查询产品点播产品信息和点播订单详情
        if(null!=vo && null!=vo.getProductId()){
            //查询点播商品信息
            LambdaQueryWrapper<YxVodProductEntity> proWapper=new LambdaQueryWrapper();
            proWapper.eq(YxVodProductEntity::getVideoId,videoId);
            proWapper.eq(YxVodProductEntity::getStatus,CommonConstant.ONE);
            YxVodProductEntity proEntity = vodProductMapper.selectOne(proWapper);
            if(null!=proEntity){
                vo.setProductId(proEntity.getProductId());
                vo.setProductMasterPic(proEntity.getProductMasterPic());
                vo.setProductName(proEntity.getProductName());
                vo.setPrice(proEntity.getPrice());
            }
            //查询卡片点击信息
            VodSalesRevenueVo clickVo=vodProductClickMapper.getClickCntByProductId(vo.getProductId(),videoId);
            Integer clickCnt = clickVo.getClickCnt();
            //转换率：购买次数\点击次数
            if(0!=clickCnt){
                Integer buyCnt = vo.getBuyCnt();
                vo.setClickBuyRate(String.format("%.2f",buyCnt/clickCnt*100.00)+"%");
            }else{
                vo.setClickBuyRate("0%");
            }
            vo.setClickCnt(clickCnt);
            vo.setUserClickCnt(clickVo.getUserClickCnt());
            vo.setVideoId(videoId);
        }
        return vo;
    }
    //--------------------------------------------------------------------------------------------------------------------------
}
